package com.artisan.web.shiro;
import com.artisan.common.enums.RoleEnum;
import com.artisan.common.utils.MD5;
import com.artisan.medium.admin.pojo.ShiroUser;
import com.artisan.medium.admin.service.UserService;
import com.artisan.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.tools.ant.types.selectors.SizeSelector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.reflect.generics.tree.ByteSignature;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * xierongxian
 * 2016-11-13
 * shiro登录验证
 */
@Component
public class UserRealm extends AuthorizingRealm{
    @Autowired
    private UserService userService;


    /***
     * shiro授权
     * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        User user =  (User) principalCollection.getPrimaryPrincipal();
        HashSet<String> hashSet=new HashSet<String>();
        //设置用户角色类型
        info.addRole(RoleEnum.getByValue(String.valueOf(user.getRoleId())).getMessage());
        if(user.getRoleId().equals("1")){
            hashSet.add("*:*");
        }else{
            List<Map<String,String>> listMap=userService.searchUserAuth(user.getId());
            for(Map map:listMap){
                if(map.get("PERMISSION")!=null&&!"".equals(map.get("PERMISSION"))){
                    hashSet.add(map.get("PERMISSION").toString());
                }
            }
        }
        info.setStringPermissions(hashSet);
        return info;
    }
    /**
     * shiro认证
     * */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)throws  AuthenticationException{
        //获取用户名
        String username=token.getPrincipal().toString();
        //获取凭证密码
        String password=new String((char[])token.getCredentials());
        //数据库验证邮箱密码是否存在
       // password=MD5.MD5(password);
        User shiroUser=userService.checkLogin(username, MD5.MD5(password));
        if(shiroUser==null){
            throw new UnknownAccountException();
        }else{
            if(shiroUser.getState().equals("0")){
                //锁定停用
                throw new DisabledAccountException();
            }else{
                //操作session
                SecurityUtils.getSubject().getSession().setAttribute("shiroUser",shiroUser);
            }
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(shiroUser,shiroUser.getPassword(),this.getName());
        SecurityUtils.getSubject();
        return info;
    }
}
